package com.zz.cogo.auth.controller;

import com.zz.cogo.account.bo.UserLoginBo;
import com.zz.cogo.account.vo.AuthVo;
import com.zz.cogo.auth.client.UserClient;
import com.zz.cogo.auth.config.JwtProperties;
import com.zz.cogo.common.auth.entity.UserInfo;
import com.zz.cogo.common.auth.utils.JwtUtils;
import com.zz.cogo.common.vo.CommonVo;
import com.zz.cogo.common.vo.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClasName UserController
 * @Descripution TODO
 * @Author leikw
 * @Date 2021/11/18 17:22
 * @Version V1.0
 */

@EnableConfigurationProperties(JwtProperties.class)
@RestController
@RequestMapping("/auth")
public class AuthController {

//    eyJhbGciOiJSUzI1NiJ9.eyJpZCI6NTMwOTg0MjI4ODA1Nzk1ODQsInVzZXJuYW1lIjoiMjIyIiwiZXhwIjoxNjM3MzA2Njk0fQ.ve58fW25h9FZL4LoUywnA72sOhuw8K88ZQpKd6hHmhSkhKHyJO0XMWFwWB03aahBARrNHTw9EXbxsAzhvLQpRYIBg_jPl9_yFuSsF4fJSdm8dTmAabwlojoOviMoGDrGA1aRH9PVMh60rNr1wh-0ikxtuqZxacJgR3dSJK3p3IQ

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProperties;

    @GetMapping("/accredit")
    public CommonVo<String> accredit(UserLoginBo userLoginBo){
        System.out.println(userLoginBo);
        CommonVo<AuthVo> authVoCommonVo = userClient.queryByAuth(userLoginBo);

        AuthVo content = authVoCommonVo.getContent();

        String result = authVoCommonVo.getResult();

        if(result.equals(ResultCode.SUCCESS.getCode())){
            //认证成功，生成token
            try {
                String token = JwtUtils.generateToken(new UserInfo(content.getUid(),content.getUserName()),
                        jwtProperties.getPrivateKey(), jwtProperties.getExpire()
                );

                return new CommonVo<String>(ResultCode.SUCCESS,token);
            } catch (Exception e) {
                //生成失败
                return null;
            }

        }else{
            //认证失败
            return new CommonVo<>(ResultCode.UNAUTH);
        }
    }

}
